<?php
namespace app\api\logic;

use app\api\cache\Marketing;
use app\api\consDir\ErrorConst;
use app\api\consDir\OrderPrefixConst;
use app\api\consDir\SandConst;
use app\api\services\CartService;
use app\api\services\CouponService;
use app\api\services\MemberService;
use app\api\services\OrderService;
use app\api\services\PayService;
use app\api\services\SandService;
use app\api\services\ShopService;
use app\common\libs\Singleton;
use app\common\models\CouponMember;
use app\common\models\Member\Member;
use app\common\models\Order\Order;
use app\common\models\Order\OrderAddress;
use app\common\models\Order\OrderGoods;
use app\common\models\Order\OrderShop;
use app\common\models\Service\Service;
use app\common\models\Shop\Shop;
use app\common\utils\CommonUtil;
use app\common\utils\RedLock;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

/**
 * 订单模块
 * Class MemberLogic
 * @package app\api\logic
 */
class OrderLogic extends BaseLogic
{
    use Singleton;

    /**
     * 确认收货
     * @param  [type] $orderNo [description]
     * @return [type]          [description]
     */
    public function taskOrder($orderNo): bool
    {
        if ( ! RedLock::getInstance()->lock('taskOrder_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        //0待支付 1待发货 2待收款 3已收货 4已完成 5退款中 6退款成功 7取消 8超时取消 9待退货
        $order = OrderService::getInstance()->getOrderInfo($orderNo, $this->userinfo->id);
        if (empty($order)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if ($order['status'] != 2) {
            CommonUtil::throwException(ErrorConst::ORDER_STATUS_ERROR, ErrorConst::ORDER_STATUS_ERROR_MSG);
        }
        $task = OrderService::getInstance()->taskOrder($order, $this->userinfo->id);
        if (empty($task)) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }
        // 检查会员等级升级
        try {
            \app\api\services\UserLevelService::getInstance()->checkUpgrade(
                $this->userinfo->id
            );
        } catch (\Exception $e) {
            \think\facade\Log::error($e->getMessage());
        }
        return true;
    }

    /**
     * @param $orderNo
     * @param $goodsId
     * @return array|mixed|void
     */
    public function orderExpress($orderNo, $goodsId)
    {
        $order = OrderService::getInstance()->getOrderInfo($orderNo, $this->userinfo->id);
        if (empty($order)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        return OrderService::getInstance()->orderExpress($orderNo, $goodsId);
    }


    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function orderDetail($orderNo): array
    {
        // $this->userinfo->id = 1000031;
        $order = OrderService::getInstance()->getOrderInfo($orderNo, $this->userinfo->id);
        if (empty($order)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        $expireTime            = strtotime($order['expireAt']) - time();
        $order['deliveryType'] = '普通快递';
        $order['expireTime']   = $expireTime > 0 ? $expireTime : 0;
        $orderAddress          = OrderService::getInstance()->getOrderAddress($orderNo);

        $orderShop   = OrderService::getInstance()->getOrderShopInfo($orderNo);
        $supplyGoods = OrderGoods::getInstance()->where('order_no', $order['orderNo'])->select();

        $serviceInfo = [
            'phone'  => 18938511389,
            'wechat' => 'rxx',
        ];
        $serviceInfos = Service::getInstance()->where('id',$order['serviceId'])->find();
        $serviceInfos = !empty($serviceInfos) ? $serviceInfos->toArray() : [];
        return [
            'orderInfo'    => $order,
            'orderAddress' => $orderAddress,
            'orderShop'    => $orderShop,
            'serviceInfo'  => $serviceInfo,
            'supplyGoods'  => $supplyGoods,
            'serviceInfos' => $serviceInfos,
        ];
    }

    public function delOrder($orderNo): bool
    {
        $order = OrderService::getInstance()->getOrderInfo($orderNo, $this->userinfo->id);
        if (empty($order)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if ( ! in_array($order['status'], [0, 4, 6, 7, 8])) {
            CommonUtil::throwException(ErrorConst::ORDER_STATUS_ERROR, ErrorConst::ORDER_STATUS_ERROR_MSG);
        }
        OrderService::getInstance()->delOrder($order);
        return true;
    }

    /**
     * 取消不需要退款
     * @param $orderNo
     * @return bool
     */
    public function cancellationOrder($orderNo): bool
    {
        $order = OrderService::getInstance()->getOrderInfo($orderNo, $this->userinfo->id);
        if (empty($order)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if ($order['status'] != 0) {
            CommonUtil::throwException(ErrorConst::NO_ORDER_ERROR, ErrorConst::NO_ORDER_ERROR_MSG);
        }

        $update = [
            'status'    => 7,
            'refund_at' => date('Y-m-d H:i:s'),
        ];
        $where = [
            ['order_no', '=', $orderNo],
            ['status', '=', 0],
        ];
        Order::getInstance()->where($where)->update($update);
        OrderShop::getInstance()->where($where)->update($update);
        OrderGoods::getInstance()->where($where)->update($update);
        //退回优惠券
        $where = [
            ['id', 'in', $order['couponId']],
        ];
        CouponMember::getInstance()->where($where)->update(['status' => 0, 'update_at' => date('Y-m-d H:i:s')]);
        return true;
    }

    /**
     * 取消并退款
     * @param $orderNo
     * @return bool
     */
    public function cancelOrder($orderNo): bool
    {
        $order = OrderService::getInstance()->getOrderInfo($orderNo, $this->userinfo->id);
        if (empty($order)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        if ($order['status'] != 1) {
            CommonUtil::throwException(ErrorConst::NO_ORDER_ERROR, ErrorConst::NO_ORDER_ERROR_MSG);
        }

        //30分钟
        $date = date('Y-m-d H:i:s', strtotime('-30 minutes'));
        if ($order['payAt'] < $date) {
            CommonUtil::throwException(ErrorConst::ORDER_TIME_ERROR, ErrorConst::ORDER_TIME_ERROR_MSG);
        }
        //退款逻辑
        $refund = OrderService::getInstance()->orderRefund($order);
        if ( ! $refund) {
            CommonUtil::throwException(ErrorConst::ORDER_REFUND_ERROR, ErrorConst::ORDER_REFUND_ERROR_MSG);
        }

        return true;
    }

    /**
     * @param $type
     * @param $orderType
     * @param $page
     * @param $pageSize
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderList($type, $orderType, $page, $pageSize): array
    {
        $list = OrderService::getInstance()->orderList($this->userinfo->id, $type, $orderType, $page, $pageSize);
        return ['rows' => $list];
    }

    /**
     * @param $shopId
     * @param float|int $price
     * @param int $skuId
     * @param string $couponId
     * @return array
     */
    public function createOutlineOrder($shopId, float $price = 0, int $skuId = 0, string $couponId = '', $option = [], $deduction = 0, $payPrice): array
    {
        if ($price <= 0) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        if ( ! RedLock::getInstance()->lock('createOutlineOrder_' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }

        $shopInfo = ShopService::getInstance()->getShopInfoById($shopId,'*');
        if (empty($shopInfo) || $shopInfo['status'] != 1) {
            CommonUtil::throwException(ErrorConst::NO_SHOP_ERROR, ErrorConst::NO_SHOP_ERROR_MSG);
        }

        if($deduction > 0){
            $finance = MemberService::getInstance()->finance($this->userinfo->id);
            if($finance['deduction'] < $deduction){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '平台抵扣券不足');
            }
            $config = Marketing::getKeyData('marketing', 'deduction');
            if(isset($config['status']) && $config['status'] == 1){
                if($price >= $config['offline_max']){
                    //限制
                    if($config['offline_limit_type'] == 0){
                        //金额
                        if($config['offline_type'] == 0){
                            if($deduction > $config['offline_value']){
                                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '超过最大抵扣金额');
                            }
                        }else{
                            //比例
                            if($config['supply_rate'] > 0){
                                $can = bcmul($price,$config['offline_rate']*0.01,2);
                                if($deduction > $can){
                                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '超过最大抵扣金额');
                                }
                            }
                        }
                    }
                }
            }else{
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '未启用平台抵扣券');
            }
            /*$deductionPrice = bcsub($price,$deduction,2);
            if($payPrice != $deductionPrice){
                Log::error("createOutlineOrder:前端payPrice".);
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '价格错误');
            }*/
        }

        $order = OrderService::getInstance()->createOutlineOrder(
            $shopInfo,
            $this->userinfo->id,
            $price,
            $skuId,
            $couponId,
            $option,
            $deduction,
        );
        if ( ! $order) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }
        return ['orderNo' => $order];
    }

    /**
     * @param $goodsInfo
     * @param $addressId
     * @param $orderType
     * @param float|int $price
     * @param float|int $amount
     * @param string $couponId
     * @param string $userNotes
     * @param array $option
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createOrder($goodsInfo, $addressId, $orderType, float $price = 0, float $amount = 0, string $couponId, $userNotes = '', $deduction = 0, $option = [],$take = []): array
    {
        if ($price < 0) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        if ( ! RedLock::getInstance()->lock('createOrder:' . $this->userinfo->id, 1)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $goodsInfo = json_decode($goodsInfo, true);
        $goodsCart = $goodsInfo;
        if (empty($goodsInfo)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        $goodsList = OrderService::getInstance()->getOrderGoodsInfo($goodsInfo);
        if (empty($goodsList)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        [$level_discount, $coupon_discount_both] = \app\api\services\UserLevelService::getInstance()->levelDiscount(
            $this->userinfo->id
        );
        $option['level_discount']       = $level_discount;
        $option['coupon_discount_both'] = $coupon_discount_both;

        $priceInfo = OrderService::getInstance()->getOrderPrice($goodsList, $this->userinfo->id, $option);
        // 使用优惠类型：  coupon | discount | coupon_discount | '' 空字符串表示不需要优惠
        $useSale = $option['useSale'] ?? 'unknow';
        if ($useSale == '' || $useSale == 'discount') {
            $couponId = '';
        }
        if ( ! empty($couponId)) {
            $couponInfo = CouponService::getInstance()->getCouponInfo($couponId, $this->userinfo->id);
            if (empty($couponInfo)) {
                CommonUtil::throwException(ErrorConst::COUPON_ERROR, ErrorConst::COUPON_ERROR_MSG);
            }
            $ret = CouponService::getInstance()->checkOrderCoupon($couponInfo, 1, $goodsList);
            if ( ! $ret) {
                CommonUtil::throwException(
                    ErrorConst::COUPON_ERROR,
                    '优惠券使用范围受限');
            }
            /*
            if ($priceInfo['allList']['pay_price'] < $couponInfo['full_amount']) {
                CommonUtil::throwException(ErrorConst::COUPON_NO_ERROR, ErrorConst::COUPON_NO_ERROR_MSG);
            }
            $couponAmount = $couponInfo['amount'];
            */
            CouponService::getInstance()->getCouponPrice($priceInfo, $couponId, $this->userinfo->id);
        }
        $price = bcadd($price, $amount, 2);
        // var_dump($priceInfo['shopPriceList'][0]['pay_price'] != $price, $priceInfo['shopPriceList'][0]['pay_price'], $price);exit;

        //平台抵扣券
        if($deduction > 0){
            $finance = MemberService::getInstance()->finance($this->userinfo->id);
            if($finance['deduction'] < $deduction){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '平台抵扣券不足');
            }
            $config = Marketing::getKeyData('marketing', 'deduction');
            if(isset($config['status']) && $config['status'] == 1){
                if($priceInfo['allList']['sell_price'] >= $config['order_max']){
                    //限制
                    if($config['order_limit_type'] == 0){
                        //金额
                        if($config['order_type'] == 0){
                            if($deduction > $config['order_value']){
                                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '超过最大抵扣金额');
                            }
                        }else{
                            //比例
                            if($config['order_rate'] > 0){
                                $can = bcmul($priceInfo['allList']['sell_price'],$config['order_rate']*0.01,2);
                                if($deduction > $can){
                                    CommonUtil::throwException(ErrorConst::PARAM_ERROR, '超过最大抵扣比例');
                                }
                            }
                        }
                    }
                    $priceInfo['allList']['pay_price'] = bcsub($priceInfo['allList']['pay_price'],$deduction,2);
                    if($priceInfo['allList']['pay_price'] < 0){
                        $priceInfo['allList']['pay_price'] = 0;
                    }
                    $priceInfo['allList']['deduction'] = $deduction;
                    if(!empty($priceInfo['shopPriceList'])){
                        $count = count($priceInfo['shopPriceList']);
                        $divDeduction = bcdiv($deduction,$count,2);
                        foreach($priceInfo['shopPriceList'] as &$v){
                            $v['pay_price'] = bcsub($v['pay_price'],$divDeduction,2);
                            $v['deduction'] = $divDeduction;
                        }
                    }
                    if(!empty($priceInfo['goodsPriceList'])){
                        $count = count($priceInfo['goodsPriceList']);
                        $divDeduction = bcdiv($deduction,$count,2);
                        foreach($priceInfo['goodsPriceList'] as &$v){
                            $v['pay_price'] = bcsub($v['pay_price'],$divDeduction,2);
                            $v['deduction'] = $divDeduction;
                        }
                    }
                }
            }

        }
        Log::error($priceInfo['allList']['pay_price'].'=='.$price);
        if ($priceInfo['allList']['pay_price'] != $price) {
            Log::error('优惠明细：'.json_encode($priceInfo));
            CommonUtil::throwException(ErrorConst::PRICE_ERROR, ErrorConst::PRICE_ERROR_MSG);
        }
        if ($amount > 0) {
            $finance = MemberService::getInstance()->finance($this->userinfo->id);
            if ($amount > $finance['amount']) {
                CommonUtil::throwException(ErrorConst::NO_PRICE_ERROR, ErrorConst::NO_PRICE_ERROR_MSG);
            }
            $priceInfo['allList']['pay_price']  = bcsub($priceInfo['allList']['pay_price'], $amount, 2);
            $priceInfo['allList']['pay_amount'] = $amount;
        }



        $addressInfo = MemberService::getInstance()->addressDetail($this->userinfo->id, $addressId, 2);
        if (empty($take['serviceId']) && empty($addressInfo) && $orderType == 1) {
            CommonUtil::throwException(ErrorConst::NO_ADDRESS_ERROR, ErrorConst::NO_ADDRESS_ERROR_MSG);
        }
        $priceInfo['allList']['user_note'] = $userNotes;

        //自提
        $priceInfo['allList']['take_mobile'] = $take['takeMobile'] ?? '';
        $priceInfo['allList']['service_id'] = $take['serviceId'] ?? 0;
        $priceInfo['allList']['take_time'] = $take['takeTime'] ?? '';

        $order = OrderService::getInstance()->createOrder($priceInfo, $addressInfo, $couponId);

        if ( ! $order) {
            CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
        }

        $isBalance = 0;
        if ($priceInfo['allList']['pay_price'] == 0) {
            $isBalance = 1;
            $pay       = PayService::getInstance()->payOrder($this->userinfo->id, $priceInfo['allList'], 2);
            $info      = [
                'pay_status'   => 2,
                'pay_no'       => $pay['pay_no'],
                'money'        => $pay['pay_amount'],
                'trade_no'     => '',
                'receipt_data' => '',
            ];
            $info = PayService::getInstance()->payFormOrder($info);
            if ( ! $info) {
                CommonUtil::throwException(ErrorConst::SYSTEM_ERROR, ErrorConst::SYSTEM_ERROR_MSG);
            }
        }

        //$goodsCart
        CartService::getInstance()->delCart($goodsCart, $this->userinfo->id);

        return ['isBalance' => $isBalance, 'orderNo' => $order, 'expireAt' => $priceInfo['allList']['expire_at']];
    }

    /**
     * 预计送到时间
     * @param  [type] $sendCity  [description]
     * @param  [type] $addressId [description]
     * @return [type]            [description]
     */
    public function estimatedDelivery($sendCity, $addressId, $startDate = null, $days = 3)
    {
        $city = '';
        if (is_numeric($sendCity)) {
            $sendCity = \think\facade\Db::table('member_shop')
                ->where('id', $sendCity)
                ->value('city');
        }
        if (empty($startDate)) {
            $startDate = new \DateTime();
        }
        $startDate->modify("+{$days} day");
        $tips = '预计' . $startDate->format('n月j日') . '后送达';
        if (is_numeric($addressId)) {
            // var_dump($sendCity);exit;
            $city = \app\common\models\Member\Address::where('id', $addressId)
                ->value('city');
        } else if (is_string($addressId)) {
            $city = $addressId;
        }
        // 同城3天，不同城5天送达
        if ($city != $sendCity) {
            $startDate->modify("+2 day");
            $tips = '预计' . $startDate->format('n月j日') . '后送达';
        }
        return $tips;
    }

    /**
     * @param $goodsInfo
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderPreview($goodsInfo, $couponId = ''): array
    {
        $goodsInfo = json_decode($goodsInfo, true);
        if (empty($goodsInfo)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }
        //获取订单信息
        $goodsList = OrderService::getInstance()->getOrderGoodsInfo($goodsInfo);
        if (empty($goodsList)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, ErrorConst::PARAM_ERROR_MSG);
        }

        [$level_discount, $coupon_discount_both] = \app\api\services\UserLevelService::getInstance()->levelDiscount(
            $this->userinfo->id
        );
        $priceInfo = OrderService::getInstance()->getOrderPrice(
            $goodsList,
            $this->userinfo->id,
            [
                // 预览的时候不需要算折扣优惠
                // 'level_discount' => $level_discount,
            ]);

        // 预览的时候不需要算优惠券优惠
        // if ( ! empty($couponId)) {
        // CouponService::getInstance()->getCouponPrice($priceInfo, $couponId, $this->userinfo->id);
        // }

        $finance = MemberService::getInstance()->finance($this->userinfo->id);

        $return = empty($goodsList) ? [] : array_values($goodsList);
        // 订单预览新增响应“levelDiscount和couponDiscountBoth”，当 levelDiscount>0 并且 couponDiscountBoth == 0 的时候，需要前端给用户选择使用优惠券还是折扣率

        $config= Marketing::getKeyData('marketing', 'deduction');
        return [
            'levelDiscount'      => $level_discount,
            'couponDiscountBoth' => $coupon_discount_both,
            'rows'               => $return,
            'finance'            => $finance,
            'postage'            => $priceInfo['allList']['postage'],
            'sale'               => $priceInfo['allList']['sale'],
            'sellPrice'          => $priceInfo['allList']['sell_price'],
            'payPrice'           => $priceInfo['allList']['pay_price'],
            'deductionConfig'    => $config,
        ];
    }

    /**
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function offlineCheck($orderNo): bool
    {
        $where = [
            ['order_no', '=', $orderNo],
            ['order_type', '=', 3]
        ];
        $orderData = Order::getInstance()->where($where)->find();
        if (empty($orderData)) {
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '自提订单不存在');
        }

        Order::getInstance()->startTrans();
        try{
            $update = [
                'status'  => 4, //完成
                'task_at' => date('Y-m-d H:i:s'),
                'completion_at' => date('Y-m-d H:i:s')
            ];
            //修改主单状态
            Order::getInstance()->where($where)->update(array_merge($update,['check_user_id' => $this->userinfo->id]));
            OrderGoods::getInstance()->where($where)->update($update);
            OrderShop::getInstance()->where($where)->update($update);
            OrderService::getInstance()->dividend($orderData);
            $subOrderItems = OrderShop::getInstance()->where($where)->select();
            if (!empty($subOrderItems)) {
                $msg = '线下支付订单';
                foreach ($subOrderItems as $key => $subItem) {
                    $shopId = $subItem['shopId'];
                    $price = $subItem['payPrice'];
                    //线下货款
                    $shop = Shop::getInstance()->where('id', $shopId)->find();
                    // 扣除让利
                    // platformFee 让利比例
                    if ($orderData['order_type'] == 1) {
                        $subItem['sellPrice'] = $subItem['payPrice'];
                    }
                    $reduceMoney = bcmul($subItem['sellPrice'], $shop['platformFee'] * 0.01, 2);
                    // 线下货款 = 实付金额 - 让利金额(sellPrice * 让利比例) + 平台优惠 + 优惠折扣(用户等级优化折扣)
                    //$goodsMoney = $subItem['payPrice'] - $reduceMoney + $subItem['platformSale'] + ($subItem['discountSale'] ?? 0);
                    $goodsMoney = $subItem['payPrice'] - $reduceMoney + $subItem['platformSale'] + ($subItem['discountSale'] ?? 0);
                    MemberService::getInstance()->addFinanceLog($shop['userId'], 'order_task', $goodsMoney, 2, $msg);

                    //商家后台积分赠送比例，是用户获得数字积分的比例，比如设置为10% ，即用户消费100 可获得10个数字积分
                    $gxzRate = OrderGoods::getInstance()->where(['order_no' => $orderNo, 'shop_id' => $shopId])->value('gxz_rate');
                    if ($gxzRate > 0) {
                        $shop['gxzRate'] = $gxzRate;
                    }
                    if ($shop['gxzRate'] > 0) {
                        $money = bcmul($price, $shop['gxzRate'] * 0.01, 4);
                        if ($money > 0) {
                            //$msg = '购买商品，赠送数字积分';
                            //MemberService::getInstance()->addFinanceLog($orderData['userId'], 'offline', $money, 6, $msg, $orderNo, 2);
                            $msg = '线下订单消费，赠送贡献值，订单号' . $orderNo;
                            MemberService::getInstance()->addFinanceLog($subItem['userId'], 'offline', $money, 7, $msg, $orderNo);
                        }
                    }
                    //加入分润池
                    $profit = bcmul($price, $shop['platformFee'] * 0.01, 4);
                    MemberService::getInstance()->profitPoolLog($subItem['userId'], $subItem['payPrice'], $orderNo, $profit, 2);

                    if($orderData['isDirect'] == 0){
                        Log::info($orderNo . '公司杉德账号转账给用户' . $goodsMoney);
                        //$goodsAllAmount = env('test.is_test') ? 0.01 : $goodsAllAmount;
                        $ret = SandService::getInstance()->transfer($goodsMoney, env('sand.consumeMid'), SandConst::PREFIX . $shop['userId'], 0, getNo(OrderPrefixConst::TR));
                        if (!isset($ret['code']) || $ret['code'] != 1) {
                            throw new Exception($orderNo . $ret['data']);
                        }
                    }else{
                        //解冻
                        Log::info($orderNo . '解冻用户金额' . $goodsMoney);
                        //$goodsAllAmount = env('test.is_test') ? 0.01 : $goodsAllAmount;
                        $ret = SandService::getInstance()->unfreeze(getNo('unFreeze'),$subItem['freezeOrderNo'],$goodsMoney);
                        if (!isset($ret['resultStatus']) || $ret['resultStatus'] != 'success') {
                            throw new Exception($orderNo . $ret['errorDesc']);
                        }
                    }
                }
            }
        }catch(\Exception $e){
            Order::getInstance()->rollback();
        }
        Order::getInstance()->commit();


        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function checkOrderDetail($orderNo): array
    {
        $where = [
            ['order_no', '=', $orderNo],
        ];
        $order = Order::getInstance()
            ->where($where)
            ->field('id,status,order_no,user_id,sell_price,order_type,pay_price,postage,sale,completion_at,pay_at,create_at,expire_at,is_comment,check_user_id,service_id,check_user_id')
            ->order('id desc')
            ->find();
        if (empty($order)) {
            return [];
        }
        $order = $order->toArray();
        $shopId = Shop::getInstance()->where('user_id',$this->userinfo->id)->value('id');
        $map = [
            ['order_no', '=', $orderNo],
            ['shop_id','=',$shopId]
        ];
        $orderShop = OrderShop::getInstance()->where($map)->find();
        if(empty($orderShop)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '订单不存在');
        }
        // 供应商订单 没有 orderShop 数据，没有 shop_id
        if (empty($orderShop['shopId'])) {
            $order['shopInfo'] = [];
        } else {
            $order['shopInfo'] = ShopService::getInstance()->getShopInfoById(
                $orderShop['shopId'],
                'id,shop_logo,shop_name,kf_phone');
        }
        $orderInfo = OrderGoods::getInstance()->where($where)->field('is_freight_insurance,is_seven,status,quantity,sell_price,goods_id,goods_title,sku_title,goods_img')->select();
        $order['goodsInfo'] = $orderInfo;
        $checkInfo = Member::getInstance()->where('id',$order['checkUserId'])->field('id,user_name,phone')->find();
        $checkInfo = !empty($checkInfo) ? $checkInfo : [];
        //核销人信息
        $order['checkInfo'] = $checkInfo;
        //买家信息
        $buyInfo = Member::getInstance()->where('id',$order['userId'])->field('id,user_name,phone')->find();
        $buyInfo = !empty($buyInfo) ? $buyInfo : [];
        $order['buyInfo'] = $buyInfo;

        //快递地址
        $order['addressInfo'] = OrderAddress::getInstance()->where('order_no',$orderNo)->find();

        return $order;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function checkList($page, $pageSize): array
    {
        $where = [
            ['check_user_id', '=', $this->userinfo->id]
        ];
        $list = Order::getInstance()
            ->where($where)
            ->page($page, $pageSize)
            ->field('id,status,order_no,user_id,sell_price,order_type,pay_price,postage,sale,pay_at,create_at,expire_at,is_comment,completion_at,check_user_id')
            ->order('completion_at desc,id desc')
            ->select();
        if (empty($list)) {
            return [];
        }
        $list = $list->toArray();

        foreach ($list as &$val) {
            $where = [
                ['order_no', '=', $val['orderNo']],
            ];
            $orderShop = OrderShop::getInstance()->where($where)->find();
            // 供应商订单 没有 orderShop 数据，没有 shop_id
            if (empty($orderShop['shopId'])) {
                $val['shopInfo'] = [];
            } else {
                $val['shopInfo'] = ShopService::getInstance()->getShopInfoById(
                    $orderShop['shopId'],
                    'id,shop_logo,shop_name,kf_phone');
            }

            $orderInfo = OrderGoods::getInstance()->where($where)->field('is_freight_insurance,is_seven,status,quantity,sell_price,goods_id,goods_title,sku_title,goods_img')->select();
            $val['goodsInfo'] = $orderInfo;
            $val['checkInfo'] = Member::getInstance()->where('id', $val['checkUserId'])->field('phone,user_name')->find();
        }
        return $list;
    }


}
